package br.com.toscano.gobra.business;

import javax.inject.Inject;

import br.com.toscano.automacao.constant.ConstantesMensagem;
import br.com.toscano.automacao.exception.DescricaoException;
import br.com.toscano.gobra.domain.ObjetoAbstrato;
import br.com.toscano.gobra.persistence.AbstractDAO;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;
import br.gov.frameworkdemoiselle.util.ResourceBundle;

@BusinessController
public class AbstractBC<OBJ extends ObjetoAbstrato, KEY extends Object, DAO extends AbstractDAO<OBJ, KEY>> extends DelegateCrud<OBJ, KEY, DAO> {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private ResourceBundle bundle;

	@Override
	public OBJ insert(OBJ bean) {
		String atributoDescriao = bean.getAtributoDescricao();
		if (atributoDescriao != null) {
			OBJ obj = this.getDelegate().consultarPorDescricao(bean.getAtributoDescricao() , bean.getValorDescricao());
			if (obj != null) {
				throw new DescricaoException(bundle.getString(ConstantesMensagem.MSG_ERRO_DESCRICAO_JA_USADA, bean.getLabelAtributoDescricao()));
			} else {
				return getDelegate().insert(bean);
			}
		} else {
			return getDelegate().insert(bean);
		}
	}

	@Override
	public OBJ update(OBJ bean) {
		String atributoDescriao = bean.getAtributoDescricao();
		if (atributoDescriao != null) {
			OBJ obj = this.getDelegate().consultarPorDescricao(bean.getAtributoDescricao() , bean.getValorDescricao());
			if (obj != null  && !obj.getKey().equals(bean.getKey())) {
				throw new DescricaoException(bundle.getString(ConstantesMensagem.MSG_ERRO_DESCRICAO_JA_USADA, bean.getLabelAtributoDescricao()));
			} else {
				return getDelegate().update(bean);
			}
		} else {
			return getDelegate().update(bean);
		}
	}
}